package com.my12306.third.service.impl;

import com.my12306.common.exception.SMSException;
import com.my12306.common.util.CommentUtils;
import com.my12306.common.util.RedisUtils;
import com.my12306.third.constant.SmsConstants;
import com.my12306.third.model.vo.SmsVo;
import com.my12306.third.service.SmsService;
import com.my12306.third.util.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author:苏牧夕
 * @Date:2020/5/14 12:31
 * @Version 1.0
 */
@Service
public class SmsServiceImpl implements SmsService, Serializable {
    public final static String rgscode = "registerCode_";
    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String sendSms(String content, String phoneNumber, String templateNo) throws SMSException {
        String code = smsUtils.sendSms(new String[]{phoneNumber}, new String[]{content}, "wan", templateNo);
        return code;
    }

    /**
     * 生成手机验证码
     *
     * @param smsVo
     * @return
     */
    @Override
    public String sendRegisterCode(SmsVo smsVo) throws SMSException {
        if (smsVo == null) {
            return null;
        }
        String code = CommentUtils.getRandomCode(6);
        smsVo.setContent(code);
        String callCode = smsUtils.sendSms(new String[]{"+86" + smsVo.getPhone()}, new String[]{smsVo.getContent()}, smsVo.getUuid(), SmsConstants.SMS_TEMPLATE_ID);
        String uuid = smsVo.getUuid();
        if (uuid != null) {
            redisUtils.set(rgscode + smsVo.getPhone() + "_" + smsVo.getUuid(), code, 3, TimeUnit.MINUTES);
        } else {
            redisUtils.set(rgscode + smsVo.getPhone(), code, 3, TimeUnit.MINUTES);
        }
        return callCode;
    }

    @Override
    public String sendMessage(List<String> phones, String context) throws SMSException {
        List<String> phonelist = phones.stream().map(x -> {
            return "+86" + x;
        }).distinct().collect(Collectors.toList());
        String callCode = smsUtils.sendSms(phonelist.toArray(new String[phonelist.size()]), new String[]{context}, "CS", SmsConstants.SMS_TEMPLATE_ID);
        return callCode;
    }
}
